/**
 * 
 */
package com.android.Utils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class HttpUtils {

	private HttpUtils() {
	}

	public static String getJSONData(String url) {
		try {
			URL requestUrl = new URL(url);
			HttpURLConnection conn = (HttpURLConnection) requestUrl.openConnection();
			conn.setConnectTimeout(5000);
			conn.setRequestMethod("GET");
			conn.setDoInput(true);
			int code = conn.getResponseCode();
			if (code == HttpURLConnection.HTTP_OK) {
				InputStream is = conn.getInputStream();
				if (is != null){
					return parseInputStream(is);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "";
	}

	private static String parseInputStream(InputStream inputStream)
			throws IOException {
		String jsonStr = "";
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		int len = 0;
		byte[] data = new byte[1024];
		try {
			while ((len = inputStream.read(data)) != -1) {
				outputStream.write(data, 0, len);
			}
			jsonStr = new String(outputStream.toByteArray(), "utf-8");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			inputStream.close();
			outputStream.close();
		}
		return jsonStr;
	}

}
